import HomeAlert from './home2Alert.js'
import { LightPrompt } from '../../components/lightPrompt/lightPrompt.js'
import { func } from 'prop-types';
import React from 'react'
import { withRouter } from 'react-router-dom'
import './home_2.less'
import axios from 'axios'
import cookies from 'js-cookie'
const mapIcon = require('../../img/mapicon.png').default

const AMap = window.AMap
class Home2 extends React.Component {
    constructor() {
        super();
        this.state = {
            icon: null,
            map: null,
            point: null,
            shopList: [],
            cityname: '',
            arr: [],
            addaddress: '',
            address: '',
            tel: '',
            sex: 0,
            name: '',
            myposition: '',
            nearposi: [],
            home2alertflag: false,
            nearByName: '',
            nowOrderShop: {},
            // 店铺街道
            shopstreet: '',
            // 点击相应的店铺保存地点名称
            addShopPois: false,
            // 是否定位成功
            getCurrentFlag: false
        }
    }
    render() {
        let { name, tel, address, home2alertflag } = this.state
        return (
            <div id="pormpt">
                <div className="Map_head" style={{ zIndex: 22 }}>
                    <div className="iconfont icon-fanhui1"
                        style={{ transform: 'rotateY(180deg)', width: '10%', lineHeight: '.8rem' }}
                        onClick={() => { this.goBack() }}></div>
                    <div style={{ width: '80%', fontSize: '.5rem', fontWeight: '600', textAlign: 'center' }}>选择店铺</div>
                    <div style={{ width: '10%' }}></div>
                </div>
                <div id="container" style={{ width: '100vw', height: '40vh' }}>


                </div>

                {
                    this.props.location.state === undefined ?
                        (this.state.getCurrentFlag === false||this.state.shopList.length===0?
                            <div style={{ fontSize: '.6rem', fontWeight: '900', winth: '100vw', textAlign: 'center' }}>正在为您努力寻找店铺...</div>
                            :
                            <div className="Map_shop">
                                <div className="Map_touchline"></div>
                                <div style={{ padding: '0 .4rem', marginTop: '.4rem' }}>
                                    <div className="Map_search_shop">
                                        <div className="Map_currentcity">
                                            <span className="iconfont icon-dingwei1" style={{ marginRight: '.4rem' }}>{this.state.cityname}</span>
                                            <i style={{ borderRight: '1px solid rgb(177, 177, 177' }}></i>
                                            <span className="iconfont icon-fangdajing" style={{ marginLeft: '.4rem' }}></span>
                                        </div>
                                    </div>
                                </div>

                                <div style={{ fontSize: '.42rem', fontWeight: '600', padding: '0 .4rem' }}>附近餐厅</div>
                                {
                                    this.state.shopList.map((item, index) => {
                                        return <div key={index} className="Map_shop_every"
                                            onClick={() => { this.mapSearch(item.store_site, index, item) }}

                                        >
                                            <div>
                                                <div style={{ fontSize: '.4rem', fontWeight: '600' }}>{item.store_mess}</div>
                                                <div>{item.store_name}</div>
                                            </div>
                                            <div>
                                                <div className="iconfont icon-iconcopy1" style={{ textAlign: 'right', fontSize: '.6rem' }}
                                                    onClick={() => { this.shopData(item) }}>

                                                </div>
                                                <div style={{ marginTop: '-0.2rem' }}>距离您{item.dis}m</div>
                                            </div>

                                        </div>
                                    })
                                }
                                <div className="Map_go_order" onClick={() => { this.goOrder() }}>去点餐</div>
                            </div>)
                        //选择地址dom
                        : <div className="addaddress">
                            <div className="Map_touchline"></div>
                            {this.state.nearposi.length === 0 ?
                                <div style={{ paddingLeft: '.4rem', fontSize: '.45rem', fontWeight: '600' }}>正在搜寻附近地址</div> : <div
                                    className="Map_nearby">
                                    <div ref={(nearByName) => { this.nearByName = nearByName }}>
                                        {this.state.nearByName}
                                    </div>
                                    <div onClick={() => { this.nearBy() }}>更换地址</div>
                                </div>
                            }
                            <div className="addaddress_con_1">
                                <div>详细地址</div>
                                <input type="text"
                                    placeholder="楼号/门牌号"
                                    ref={(inp) => { this.inp = inp }}
                                    onChange={(e) => { this.setFormData(e, 'address') }}
                                    value={this.state.address} />
                            </div>
                            <div className="addaddress_con_1">
                                <div>联系人</div>
                                <input type="text"
                                    placeholder="请填写姓名"
                                    ref={(Nameinp) => { this.Nameinp = Nameinp }}
                                    onChange={(e) => { this.setFormData(e, 'name') }}
                                    value={this.state.name} />
                                <div className="Map_choosesex">
                                    <div onClick={() => { this.setSex(0) }}>
                                        <i className={this.state.sex === 0 ? 'ii iii' : 'ii'}></i>
                                        <span>女士</span>
                                    </div>
                                    <div onClick={() => { this.setSex(1) }}>
                                        <i className={this.state.sex === 1 ? 'ii iii' : 'ii'}></i>
                                        <span>先生</span>
                                    </div>
                                </div>
                            </div>
                            <div className="addaddress_con_1">
                                <div>手机号</div>
                                <input type="number"
                                    placeholder="请填写手机号"
                                    ref={(Numinp) => { this.Numinp = Numinp }}
                                    onChange={(e)=>{this.testTelChange(e,'tel')}}
                                    onBlur={(e) => { this.testTelBlur(e,'tel') }}
                                    value={this.state.tel} />
                            </div>
                            {
                                home2alertflag === false ? null : <HomeAlert parentInfo={{ ...this }}></HomeAlert>
                            }
                            <div className={tel === '' || name === '' || address === '' ? "Map_reserve" : "Map_reserve_choose"} onClick={() => { this.reserve() }}>保存地址</div>
                        </div>
                }

            </div>
        )
    }
    // 去点餐
    goOrder = () => {
        console.log(JSON.parse(localStorage.getItem('shopPois')))
        if (JSON.parse(localStorage.getItem('shopPois')) !== null) {
            this.props.history.go(-1)
        } else {
            alert('请先选择店铺')
        }
    }
    setFormData = (event, dataType) => {
        this.setState({ [dataType]: event.target.value })
    }
    testTelChange = (event,dataType) =>{
        this.setState({[dataType]:event.target.value},()=>{
            console.log(this.state.tel)
        })
    }
    testTelBlur = (event,dataType) =>{
        let testTel=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if(testTel.test(event.target.value)===true){
            this.setState({[dataType]:event.target.value})
        }else{
            console.log(testTel.test(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/))
            // alert('请输入正确格式的手机号')
            new LightPrompt().warning({
                str:'请输入正确手机号',//想要显示的文字
                domId:'pormpt',//根节点元素的id
                cleartime:1800,//弹出时间
                click:true//是否点击弹窗消失
            })
            this.setState({[dataType]:''})
        }
    }
    getNearBy = (obj) =>{
        console.log(obj)
        this.setState({ address: obj.address + `   ` + obj.name })
        this.setState({ nearByName: obj.name })
    }
    nearBy = () => {
        this.setState({ home2alertflag: true })
    }
    closeHome2Alert = (res) => {
        this.setState({ home2alertflag: res })
    }
    setSex = (n) => {
        this.setState({ sex: n })
    }
    reserve = () => {
        let { tel, name, address } = this.state
        if (tel === '' || name === '' || address === '') {
            // console.log('填信息')
        } else {
            let { address, tel, sex, name } = this.state
            let data = {
                user_id: cookies.get('user_id'),
                site: address,
                user_phone: tel,
                user_sex: sex,
                user_name: name
            }
            console.log(data)
            new LightPrompt().loading({
                str:'添加中',
                domId:'pormpt',
                cleartime:10000,
                click:false
            })

            setTimeout(() => {
                axios({
                    url: "/api/front_end/site",
                    method: "post",
                    data

                }).then(res => {
                    console.log(res)
                    if (res.status === 200) {
                        this.props.history.go(-1)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }, 1000);

            // 
        }

    }
    componentDidMount() {
        let { map } = this.state
        let _this = this
        axios({
            url: "/api/front_end/storeList",
            method: "post",

        }).then(res => {
            // console.log(res.data.data)
            let shoplist = [];
            res.data.data.forEach((item, index) => {
                item.store_site = item.store_site.split(',')

                shoplist.push(item)
            })
            this.setState({ shopList: shoplist }, () => {
                // console.log(this.state.shopList)
                map.add(_this.makerListFun(this.state.shopList));
            })

        }).catch(err => {
            console.log(err)
        })

        //
        map = new AMap.Map('container', {
            center: [116.397128, 39.916527],
            zoom: 13,
            resizeEnable: true,
        })
        //
        map.plugin(['AMap.Geolocation'], function () {
            let geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: true,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 100000,           //定位结果缓存0毫秒，默认：0
                convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true,        //显示定位按钮，默认：true
                buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10, 40),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                // showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy: false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：falseF
            })

            map.addControl(geolocation);
            geolocation.getCurrentPosition(function (status, result) {
                if (status === 'complete') {
                    _this.setState({ getCurrentFlag: true })
                    console.log('定位成功', result, result.formattedAddress)
                    //设置默认地址
                    // _this.inp.value=result.formattedAddress
                    //长地址
                    _this.setState({ address: result.formattedAddress })
                    let myPosition = [result.position.lng, result.position.lat]
                    //城市名称
                    _this.setState({ cityname: result.addressComponent.province })
                    //我的经纬度
                    _this.setState({ myposition: myPosition })
                    //附近住宅区
                    _this.setState({ nearByName: result.addressComponent.neighborhood })
                    _this.nearyBy(myPosition)
                    distance(myPosition, _this.state.shopList)
                } else if (status === 'error') {
                    console.log('定位失败', result)
                }
            })
        })
        //地图控件
        // map.plugin(["AMap.ToolBar"],function(){
        //         //加载工具条
        //         var tool = new AMap.ToolBar();
        //         map.addControl(tool);    
        // });

        //渲染店铺列表，店铺排序
        function distance(myPosition, positionList) {
            if (Array.isArray(myPosition) !== true || Array.isArray(positionList) !== true) {
                console.error('[ERROR]:Parameter type is not an array')
                return
            } else {
                // console.log(myPosition,positionList)
                positionList.map((item, index) => {
                    return positionList[index].dis = parseInt(AMap.GeometryUtil.distance(myPosition, item.store_site))
                })

                positionList.sort((a, b) => { return a.dis - b.dis })
                _this.setState({ shopList: positionList })
            }
        }

    }
    // 获取icon图标
    setMapIcon = () => {
        let icon = new AMap.Icon({
            size: new AMap.Size(20, 25),    // 图标尺寸
            image: mapIcon,  // Icon的图像
            imageOffset: new AMap.Pixel(0, 0),  // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(20, 25)   // 根据所设置的大小拉伸或压缩图片
        })
        return icon
    }

    //获取周边店铺信息
    nearyBy = (myposition) => {
        let _this = this
        AMap.service(["AMap.PlaceSearch"], function () {
            //构造地点查询类
            let placeSearch = new AMap.PlaceSearch({
                pageSize: 5, // 单页显示结果条数
                pageIndex: 1, // 页码
                citylimit: true,  //是否强制限制在设置的城市内搜索
                // map:map, // 展现结果的地图实例
                // panel: "panel", // 结果列表将在此容器中进行展示。
                autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
            });

            placeSearch.searchNearBy('', myposition, 200, function (status, result) {
                if (_this.state.addShopPois === true) {
                    _this.setState({ shopstreet: result.poiList.pois[0].name }, () => {
                        _this.props.history.push("/settle")
                        localStorage.setItem('shopPois', JSON.stringify(_this.state.cityname + _this.state.shopstreet + '店'))
                    })
                }
                _this.setState({ nearposi: result.poiList.pois })
            });
        });
    }
    //循环渲染店铺坐标
    makerListFun = (arr) => {
        if (Array.isArray(arr) === true) {
            let markerList = []
            arr.forEach((item, index) => {
                let marker = new AMap.Marker({
                    position: new AMap.LngLat(item.store_site[0], item.store_site[1]),
                    offset: new AMap.Pixel(0, 0),
                    icon: this.setMapIcon(), // 添加 Icon 实例
                    title: '北京',
                    zoom: 13
                })
                markerList.push(marker)
                // console.log(markerList)
            })
            return markerList

        } else {
            console.error('[ERROR]:Parameter type is not an array')
        }
    }
    maps = () => {
        // console.log(mapIcon)
    }
    // 返回按钮
    goBack = () => {
        // this.props.history.push('/home')
        sessionStorage.setItem("flag", JSON.stringify(true))
        this.props.history.go(-1)
    }
    // 店铺信息按钮
    shopData = (item) => {
        sessionStorage.setItem('store_id', JSON.stringify(item.store_list_id, item))
        sessionStorage.setItem("router", JSON.stringify(this.props.history.location.pathname))
        // this.props.history.push('/storelist')

        sessionStorage.setItem("flag", JSON.stringify(false))
        this.props.history.push('/list')
    }
    // 定位店铺
    mapSearch = (p, i, ite) => {
        let _this = this
        this.setState({ addShopPois: true })
        let { map, arr, shopList } = this.state
        let P = [Number(p[0]), Number(p[1])]
        this.nearyBy(P)

        map = new AMap.Map('container', {
            center: P,
            zoom: 13,
            resizeEnable: true,
            zoomToAccuracy: true,
        })
        map.plugin(['AMap.Geolocation'], function () {
            let geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 100000,           //定位结果缓存0毫秒，默认：0
                convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true,        //显示定位按钮，默认：true
                buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10, 40),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                // showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy: false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：falseF
            })

            map.addControl(geolocation);
        })
        map.add(this.makerListFun(shopList));
        let shopDomList = document.querySelectorAll('.Map_shop_every')
        for (let i = 0; i < shopDomList.length; i++) {
            shopDomList[i].style.background = 'rgb(255,255,255)'
            // shopDomList[i].style.borderBottom='2px solid rgb(255,255,255)'
        }
        shopDomList[i].style.background = 'rgb(242,242,242)'


    }
    componentWillUnmount() {
        this.setState = () => false;
    }
}
export default withRouter(Home2)